package com.ccit.springbootlaw.mapper;

import com.ccit.springbootlaw.pojo.Law;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;

@Mapper
@Repository
public interface LawMapper {
    // 根据ID查询法律信息
    @Select("SELECT * FROM laws WHERE id = #{id}")
    Law findById(int id);

    // 根据多条件查询法律信息
    @Select("<script>" +
            "SELECT * FROM laws " +
            "WHERE 1=1 " +
            "<if test='law.title != null and law.title != \"\"'>AND title LIKE CONCAT('%', #{law.title}, '%')</if> " +
            "<if test='law.content != null and law.content != \"\"'>AND content = #{law.content}</if> " +
            "<if test='law.category != null and law.category != \"\"'>AND category = #{law.category}</if> " +
            "<if test='law.lawauthor != null and law.lawauthor != \"\"'>AND lawauthor LIKE CONCAT('%', #{law.lawauthor}, '%')</if> " +
            "<if test='law.timeliness != null and law.timeliness != \"\"'>AND timeliness LIKE #{law.timeliness}</if> " +
            "<if test='startTime != null'>AND lawtime &gt;= #{startTime}</if> " +
            "<if test='endTime != null'>AND lawtime &lt;= #{endTime}</if> " +
            "</script>")
    List<Law> findByCriteria(@Param("law") Law law, @Param("startTime") Date startTime, @Param("endTime") Date endTime);

    // 插入新的法律信息
    @Insert("INSERT INTO laws (title, content, category, lawtime, timeliness, lawauthor, created_at, updated_at) " +
            "VALUES (#{title}, #{content}, #{category}, #{lawtime}, #{timeliness}, #{lawauthor}, NOW(), NOW())")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insertLaw(Law law);

    // 更新法律信息
    @Update("<script>" +
            "UPDATE laws " +
            "<set>" +
            "<if test='title != null and title != \"\"'>title = #{title},</if>" +
            "<if test='content != null and content != \"\"'>content = #{content},</if>" +
            "<if test='category != null and category != \"\"'>category = #{category},</if>" +
            "<if test='lawtime != null'>lawtime = #{lawtime},</if>" +
            "<if test='timeliness != null'>timeliness = #{timeliness},</if>" +
            "<if test='lawauthor != null and lawauthor != \"\"'>lawauthor = #{lawauthor},</if>" +
            "updated_at = NOW()" +
            "</set>" +
            "WHERE id = #{id}" +
            "</script>")
    int updateLaw(Law law);

    // 删除法律信息
    @Delete("DELETE FROM laws WHERE id = #{id}")
    int deleteLawById(int id);

    // 查询所有法律信息
    @Select("SELECT * FROM laws")
    List<Law> findAllLaws();
}